<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

class JFX_View
{
    public $template;// name of master template file
    public $cacheId;
    public $footer; // location of footer template

    // stores paths to templates, use addTemplate() and removeTemplate()
    private $pageElements = array(
        'menu'=>array(),
        'main'=>array(),
        'top'=>array(),
        'right'=>array()
    );

    // used for stepping through templates with getNextFile()
    private $counters = array(
        'menu'=>0,
        'main'=>0,
        'top'=>0,
        'right'=>0
    );

    private $css;
    private $ieCss = array();
    private $js;
    private $ieJs = array();
    private $title;
    private $cssLinks = array();
    private $cssMedias = array();
    private $jsLinks = array();
    private $jsUrl;
    private $cssUrl;
    private $onload = array();
    private $urlParams = array();
    private $breadCrumbs = array();
    private $langFiles = array();
    private $_lang = array();
    private $headCode = array();
    private $bodyText = '';
    private $endbody = '';


    public function __construct()
    {
        $CONFIG = JFX::registry('config');
        $this->template = 'default.tpl';
        $this->cssUrl = $CONFIG->cssUrl.'/';
        $this->jsUrl = $CONFIG->jsUrl.'/';
        $this->imageUrl = $CONFIG->imageUrl.'/';
    }

    public function addJs($js)
    {
        $this->js .= $js."\n";
    }

    public function addIeCssLink($css, $iename = 'lt IE 7')
    {
        foreach($this->ieCss as $ieCss){
            if($ieCss[0] == $css) return;
        }
        $this->ieCss[] = array($css ,$iename);
    }

    public function addCss($css)
    {
        $this->css .= $css;
    }

    public function addOnload($string)
    {
        $this->onload[] = (substr($string, strlen($string))==';') ? substr(0, (strlen($string)-1), $string) : $string;
    }

    public function addJsLink($link)
    {
        $this->jsLinks[] = str_replace($this->jsUrl, '', $link);
    }

    public function addIeJsLink($js, $iename = 'lt IE 7')
    {
        foreach($this->ieJs as $ieJs){
            if($ieJs[0] == $js) return;
        }
        $this->ieJs[] = array($js ,$iename);
    }

    public function addCssLink($link, $media='all')
    {
        if(in_array(str_replace($this->cssUrl, '', $link), $this->cssLinks)) return;
        $this->cssLinks[] = str_replace($this->cssUrl, '', $link);
    }

    public function removeCssLink($link)
    {
        while($k = array_search($link, $this->cssLinks)){
            unset($this->cssLinks[$k]);
        }
        
    }
    public function removeJsLink($link)
    {
        while($k = array_search($link, $this->jsLinks)){
            unset($this->jsLinks[$k]);
        }
    }

    public function addHead($text)
    {
        $this->headCode[] = $text;
    }

    public function getHead()
    {
        $string = '';
        foreach($this->headCode as $v){
            $string .= $v;
        };
        return $string;
    }

    public function addEndBody($text){
        $this->endbody .= $text;
    }

    public function getEndBody(){
        return $this->endbody;
    }

    public function getBodyText()
    {
        $string = '';
        return $this->bodyText;
    }

    public function getJsLinks()
    {
        $CONFIG = JFX::registry('config');
        $links='';
        foreach($this->jsLinks as $link){
            if(substr($link, 0, 4)!='http') $link = $CONFIG->jsUrl.'/'.$link;
            $links .= '<script src="'.$link.'" type="text/javascript"></script>'."\n\r";
        };
        return $links;
    }

    public function getCssLinks()
    {
        $CONFIG = JFX::registry('config');
        $combinedCssLinks = array();
        $uniqueCssLinks = array();
        $links = '';
        foreach($this->cssLinks as $link){
            if(substr($link, 0, 7)=='http://' || substr($link, 0, 8) == 'https://') $uniqueCssLinks[] = $link;
            else $combinedCssLinks[] = $link;
        }

        if(count($combinedCssLinks)>0){
            $links .= '<link type="text/css" rel="stylesheet" href="'.$CONFIG->cssUrl.'/';
            $links .= implode(',', $combinedCssLinks);
            $links .= '" />'."\n";
        }
        foreach($uniqueCssLinks as $link){
            $links .= '<link type="text/css" rel="stylesheet" href="'.$link.'" />'."\n";
        }

        // print styles
//        $links .= "\n".'<link type="text/css" rel="stylesheet" href="'.$this->cssUrl.'print.css" media="print">';

        return $links;
    }

    public function getOnload()
    {
        return '';
        $onload = 'function JFXOnload(){'."\n";
        foreach($this->onload as $func){
            $onload .= $func.";\n";
        };
        $onload .= '}'."\n";
        return $onload;
    }

    public function getJs()
    {
        return '<script type="text/javascript">'.$this->js.$this->getOnload().'</script>';
    }

    public function getCss()
    {
        return '<style type="text/css">'.$this->css.'</style>';
    }

    public function getIeJsLinks()
    {
        if(count($this->ieJs)<1)return;

        $links = array();
        foreach($this->ieJs as $link){
            if(substr($link[0], 0, 7)=='http://' || substr($link[0], 0, 8) == 'https://') $links[] = $link;
            else{
                $link[0] = $this->jsUrl.ltrim($link[0], '/');
                $links[] = $link;
            }
        }
        $js = '';
        foreach($links as $ieJs){
            $js .= '<!--[if '.$ieJs[1].']>'."\n";
            $js .= '<script src="'.$ieJs[0].'" type="text/javascript" language="javascript"></script>';
            $js .= "\n".'<![endif]-->';
        };

        return $js;
    }


    public function getIeCssLinks()
    {
        if(count($this->ieCss)<1)return;
        
        $links = array();
        foreach($this->ieCss as $link){
            if(substr($link[0], 0, 7)=='http://' || substr($link[0], 0, 8) == 'https://') $links[] = $link;
            else{
                $link[0] = $this->cssUrl.ltrim($link[0], '/');
                $links[] = $link;
            }
        }
        $css = '';
        foreach($links as $ieCss){
            $css .= '<!--[if '.$ieCss[1].']>'."\n";
            $css .= '<link href="'.$ieCss[0].'" rel="stylesheet" media="all" type="text/css">';
            $css .= "\n".'<![endif]-->';
        };

        return $css;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }


    public function addTemplate($colKey, $filePath, $cacheId='', $cacheTime=86400)
    {
        if(array_key_exists($colKey, $this->pageElements)) {
            $this->pageElements[$colKey][] = array('path'=>$filePath, 'cacheId'=>$cacheId, 'cacheTime'=>$cacheTime);
        };
    }

    public function removeTemplate($colKey, $filePath)
    {
        if(!array_key_exists($colKey, $this->pageElements))return;
        $found = false;
        foreach($this->pageElements[$colKey] as $k=>$v){
            if($v == $filePath){
                $found = true;
                break;
            };
        };
        if(!$found) return;
        else unset($this->pageElements[$colKey][$k]);
        $this->pageElements[$colKey] = array_regenerate_keys($this->pageElements[$colKey]);
    }

    public function addBodyText($text)
    {
        $this->bodyText .= $text;
    }

    protected function getNextFile($colKey)
    {
        if(!array_key_exists($colKey, $this->pageElements))return false;
        if($this->counters[$colKey]>=count($this->pageElements[$colKey])){
            $this->counters[$colKey] = 0;
            return false;
        };
        $this->counters[$colKey]++;
        return $this->pageElements[$colKey][($this->counters[$colKey]-1)];
    }

    public function renderFiles($colKey){
        $smarty = JFX::registry('Smarty');
        $renderedString = '';
        while($file = $this->getNextFile($colKey)){
            if($file['cacheId']==''){
                // not cached
                $smarty->caching = 0;
                $renderedString .= $smarty->fetch($file['path']);
            }else{
                // use cache
                $smarty->caching = 2;
                $smarty->cache_lifetime($file['cacheTime']);
                $renderedString .= $smarty->fetch($file['path'], $file['cacheId']);
            };
        };

        // block elements collapse if they are empty
        $renderedString = ($renderedString == '') ? '' : $renderedString;
        return $renderedString;
    }

    /**
     *  Prepares the smarty object so it has the dirname of the page elements to render
     */
    public function prepare()
    {
        $smarty= JFX::registry('Smarty');
        $user = JFX::registry('JFX_User');
        $THEME = JFX::registry('JFX_Theme');

        $success = JFX::getSuccess();
        $error = JFX::getError();

        $pageTitle = $this->getTitle();
        $jsLinks = $this->getJsLinks()."\n".$this->getIeJsLinks();
        $cssLinks = $this->getCssLinks()."\n".$this->getIeCssLinks();
        $js = $this->getJs();
        $css = $this->getCss();
        $head = $this->getHead();
        $content = $this->getBodyText();
        $main = $this->renderFiles('main');
        $breadcrumbs = $THEME->getBreadcrumbs();
        $endBody = $this->getEndBody();

        $eParams = array(
            '_TITLE' => $pageTitle,
            '_JSLINKS' => $jsLinks,
            '_CSSLINKS' => $cssLinks,
            '_BREADCRUMBS' => $breadcrumbs,
            '_JS' => $js,
            '_CSS' => $css,
            '_HEAD' => $head,
            '_ERROR' => $error,
            '_SUCCESS' => $success,
            '_CONTENT' => $content,
            '_MAIN' => $main,
            '_END_BODY' => $endBody
        );

        JFX::hook('JFX_Core.prepareAssignPre', $eParams);

        $smarty->assign('_TITLE', $eParams['_TITLE']);
        $smarty->assign('_JSLINKS', $eParams['_JSLINKS']);
        $smarty->assign('_CSSLINKS', $eParams['_CSSLINKS']);
        $smarty->assign('_JS', $eParams['_JS']);
        $smarty->assign('_CSS', $eParams['_CSS']);
        $smarty->assign('_HEAD', $eParams['_HEAD']);
        $smarty->assign('_CONTENT', $eParams['_CONTENT']);
        $smarty->assign('_BREADCRUMBS', $eParams['_BREADCRUMBS']);
        //$smarty->assign('lang', $lang->asArray());
        $smarty->assign('_SUCCESS', $eParams['_SUCCESS']);
        $smarty->assign('_ERROR', $eParams['_ERROR']);
        $smarty->assign('_MAIN', $eParams['_MAIN']);
        $smarty->assign('_END_BODY', $eParams['_END_BODY']);


    }

}
